<template>
  <view class="login-container">
    <!-- 提示登录的图标 -->
    <uni-icons type="contact-filled" size="100" color="#afafaf"></uni-icons>
    <!-- 登录按钮 -->
    <button type="primary" @click="getUserProfile" class="btn-login">一键登录</button>
    <!-- 登录提示 -->
    <view class="tip-text">
      登陆后尽享更多权益
    </view>
  </view>
</template>

<script>
  import {mapMutations,mapState} from 'vuex'
  export default {
    name:"my-login",
    computed: {
      ...mapState('m_user',['redireactInfo'])
    },
    data() {
      return {
        
      };
    },
    methods: {
      ...mapMutations('m_user',['updateUserInfo','updateToken','updateRedireactInfo']),
      // 获取微信用户的基本信息
      getUserProfile(e){
        uni.getUserProfile({
          desc: '获取用户信息',
          success: (res) => {
            // console.log(res)
            this.updateUserInfo(res.userInfo)
            
            // 获取登录成功后的Token字符串
            this.getToken(res)
          },
          fail: (res) => {
            uni.$showMsg('您取消了登录授权！')
            return
          }
        })
      },
      
      // 调用登录接口
      async getToken(info){
        // console.log(info)
        const [err,res] = await uni.login().catch(err => err)
        // 判断是否wx.login()调用失败
        if(err || res.errMsg !== 'login:ok') return uni.$showMsg('登陆失败！')
        
        // 准备参数对象
        const query = {
          code: res.code,
          encryptedData: info.encryptedData,
          iv: info.iv,
          rawData: info.rawData,
          signature: info.signature
        }
        
        // 换取token
        const {data: loginResult} = await uni.$http.post('/api/public/v1/users/wxlogin',query)
        // console.log(loginResult)
        if(loginResult.meta.status !== 400) return uni.$showMsg('登陆失败！')
        // uni.$showMsg('登录成功')
        
        // 把token保存到vuex中
        const rid = loginResult.meta.msg.split(':')[2]
        // console.log(rid)
        this.updateToken(rid)
        
        // 登录后跳转购车页面
        this.navigateBack()
      },
      
      // 返回登录之前的页面
      navigateBack(){
        if(this.redireactInfo && this.redireactInfo.openType ==='switchTab'){
          uni.switchTab({
            url: this.redireactInfo.from,
            complete: () => {
              this.updateRedireactInfo(null)
            }
          })
        }
      }
    }
  }
</script>

<style lang="scss">
.login-container{
  position: relative;
  height: 750rpx;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  
  .btn-login{
    margin: 15px 0;
    width: 90%;
    border-radius: 100px;
    background-color: #c00000;
  }
  
  .tip-text{
    font-size: 12px;
    color: gray;
  }
  
  &::after{
    content: ' ';
    display: block;
    width: 100%;
    height: 40px;
    background-color: #f5f5f5;
    position: absolute;
    bottom: 0;
    left: 0;
    border-radius: 100%;
    transform: translateY(50%);
  }
}
</style>